package com.unisedu.oa.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

public class JwtUtils {


    /**
     * 解析jwt
     */
    public static Claims parseJWT(String jsonWebToken, String base64Security) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary(base64Security))
                    .parseClaimsJws(jsonWebToken).getBody();
            return claims;
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 构建jwt
     */
    public static String createJWT(String name, String userId, String secret) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        //生成签名密钥
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secret);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //添加构成JWT的参数
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
                .claim("loginName", name)
                .claim("id", userId)

                .signWith(signatureAlgorithm, signingKey);
        //添加Token过期时间(两个小时)
        long expMillis = nowMillis + 7200000;
        Date exp = new Date(expMillis);
        builder.setExpiration(exp).setNotBefore(now);

        //生成JWT
        return builder.compact();
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public static String validateToken(String token, String secret) {
        Claims claims = JwtUtils.parseJWT(token, secret);
        String id = claims.get("id").toString();
        String name = claims.get("loginName").toString();
        long expTime =claims.getExpiration().getTime();
        if(expTime > System.currentTimeMillis() && name != null && id!=null){
            return id;
        }else{
            return null;
        }
    }
}
